/**
 * 员工端报工模块JS - 简化版本
 */
var ScanWorkWorker = {
    // 初始化
    init: function() {
        this.bindEvents();
        this.loadStats();
    },
    
    // 绑定事件
    bindEvents: function() {
        var self = this;
        
        // 报工提交
        $(document).on('click', '.btn-submit-report', function() {
            var allocationId = $(this).data('id');
            var quantity = $(this).closest('.task-item').find('.report-quantity').val();
            self.submitReport(allocationId, quantity);
        });
        
        // 扫码报工
        $('#scan-btn').on('click', function() {
            window.location.href = 'scan';
        });
        
        // 查看详情
        $(document).on('click', '.btn-view-task', function() {
            var id = $(this).data('id');
            self.viewTaskDetail(id);
        });
        
        // 查看报工记录
        $(document).on('click', '.btn-view-records', function() {
            var id = $(this).data('id');
            self.viewReportRecords(id);
        });
        
        // 数量输入验证
        $(document).on('input', '.report-quantity', function() {
            var maxQuantity = parseInt($(this).attr('max'));
            var value = parseInt($(this).val());
            if (value > maxQuantity) {
                $(this).val(maxQuantity);
                self.showMessage('warning', '报工数量不能超过待报数量');
            }
        });
        
        // 刷新数据
        $('#refresh-btn').on('click', function() {
            self.refreshData();
        });
    },
    
    // 加载统计数据
    loadStats: function() {
        var self = this;
        $.ajax({
            url: '/index/worker/stats',
            method: 'GET',
            success: function(response) {
                if (response.code === 1) {
                    var data = response.data;
                    // 更新统计卡片
                    $('#total-tasks').text(data.total_tasks || 0);
                    $('#completed-tasks').text(data.completed_tasks || 0);
                    $('#total-quantity').text(data.total_quantity || 0);
                    $('#total-wage').text('¥' + (data.total_wage || 0).toFixed(2));
                    
                    // 更新进度条
                    var progress = data.total_tasks > 0 ? (data.completed_tasks / data.total_tasks * 100) : 0;
                    $('#task-progress').css('width', progress + '%').text(progress.toFixed(1) + '%');
                }
            },
            error: function() {
                console.log('加载统计数据失败');
            }
        });
    },
    
    // 提交报工
    submitReport: function(allocationId, quantity) {
        if (!quantity || quantity <= 0) {
            this.showMessage('warning', '请输入有效的报工数量');
            return;
        }
        
        var btn = $('.btn-submit-report[data-id="' + allocationId + '"]');
        var originalText = btn.html();
        btn.html('<i class="fa fa-spinner fa-spin"></i> 提交中...').prop('disabled', true);
        
        $.ajax({
            url: '/index/worker/submit',
            method: 'POST',
            data: {
                allocation_id: allocationId,
                quantity: quantity
            },
            success: function(response) {
                if (response.code === 1) {
                    ScanWorkWorker.showMessage('success', '报工成功！');
                    setTimeout(function() {
                        window.location.reload();
                    }, 1500);
                } else {
                    ScanWorkWorker.showMessage('error', response.msg || '报工失败');
                }
                btn.html(originalText).prop('disabled', false);
            },
            error: function() {
                ScanWorkWorker.showMessage('error', '网络错误，请重试');
                btn.html(originalText).prop('disabled', false);
            }
        });
    },
    
    // 查看任务详情
    viewTaskDetail: function(id) {
        $.ajax({
            url: '/index/worker/taskDetail',
            method: 'GET',
            data: { id: id },
            success: function(response) {
                if (response.code === 1) {
                    ScanWorkWorker.showTaskDetailModal(response.data);
                } else {
                    ScanWorkWorker.showMessage('error', response.msg || '获取详情失败');
                }
            },
            error: function() {
                ScanWorkWorker.showMessage('error', '网络错误，请重试');
            }
        });
    },
    
    // 查看报工记录
    viewReportRecords: function(id) {
        $.ajax({
            url: '/index/worker/reportRecords',
            method: 'GET',
            data: { allocation_id: id },
            success: function(response) {
                if (response.code === 1) {
                    ScanWorkWorker.showRecordsModal(response.data);
                } else {
                    ScanWorkWorker.showMessage('error', response.msg || '获取记录失败');
                }
            },
            error: function() {
                ScanWorkWorker.showMessage('error', '网络错误，请重试');
            }
        });
    },
    
    // 显示任务详情模态框
    showTaskDetailModal: function(data) {
        $('#task-detail-modal').modal('show');
        // 填充详情数据
        $('#detail-order-no').text(data.order.order_no || '');
        $('#detail-product-name').text((data.model.product.name || '') + ' - ' + (data.model.name || ''));
        $('#detail-process-name').text(data.process.name || '');
        $('#detail-quantity').text(data.quantity || 0);
        $('#detail-reported-quantity').text(data.reported_quantity || 0);
        $('#detail-remaining-quantity').text(data.remaining_quantity || 0);
        $('#detail-status').text(data.status == 0 ? '进行中' : '已完成');
        $('#detail-createtime').text(this.formatDate(data.createtime));
    },
    
    // 显示报工记录模态框
    showRecordsModal: function(data) {
        $('#records-modal').modal('show');
        var html = '';
        if (data && data.length > 0) {
            data.forEach(function(record) {
                html += '<tr>';
                html += '<td>' + ScanWorkWorker.formatDate(record.createtime) + '</td>';
                html += '<td>' + record.quantity + '</td>';
                html += '<td>¥' + (record.wage || 0).toFixed(2) + '</td>';
                html += '<td>' + (record.status == 0 ? '待确认' : '已确认') + '</td>';
                html += '<td>' + (record.remark || '无') + '</td>';
                html += '</tr>';
            });
        } else {
            html = '<tr><td colspan="5" class="text-center">暂无报工记录</td></tr>';
        }
        $('#records-list').html(html);
    },
    
    // 刷新数据
    refreshData: function() {
        this.loadStats();
        // 刷新任务列表
        if (typeof TaskTable !== 'undefined') {
            TaskTable.bootstrapTable('refresh');
        }
    },
    
    // 显示消息
    showMessage: function(type, message) {
        var alertClass = 'alert-info';
        switch(type) {
            case 'success':
                alertClass = 'alert-success';
                break;
            case 'warning':
                alertClass = 'alert-warning';
                break;
            case 'error':
                alertClass = 'alert-danger';
                break;
        }
        
        var alertHtml = '<div class="alert ' + alertClass + ' alert-dismissible fade show" role="alert">' +
            message +
            '<button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>' +
            '</div>';
        
        // 显示在页面顶部
        $('body').prepend(alertHtml);
        
        // 3秒后自动消失
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 3000);
    },
    
    // 格式化日期
    formatDate: function(timestamp) {
        if (!timestamp) return '';
        var date = new Date(timestamp * 1000);
        return date.getFullYear() + '-' + 
               String(date.getMonth() + 1).padStart(2, '0') + '-' + 
               String(date.getDate()).padStart(2, '0') + ' ' +
               String(date.getHours()).padStart(2, '0') + ':' + 
               String(date.getMinutes()).padStart(2, '0');
    }
};

// 页面加载完成后初始化
$(document).ready(function() {
    ScanWorkWorker.init();
    
    // 报工表单处理
    var reportForm = document.getElementById('reportForm');
    if(reportForm){
        reportForm.addEventListener('submit', function(e){
            e.preventDefault();
            
            // 验证图片
            var input = document.getElementById('images');
            var files = input && input.files ? Array.from(input.files) : [];
            if(files.length > 9){
                alert('最多只能上传9张图片');
                return;
            }
            
            for(let i=0; i<files.length; i++){
                if(files[i].size > 10*1024*1024){
                    alert('图片不能超过10M');
                    return;
                }
            }
            
            // 提交表单
            var formData = new FormData(reportForm);
            var btn = reportForm.querySelector('button[type=submit]');
            var originalText = btn.innerHTML;
            btn.innerHTML = '提交中...';
            btn.disabled = true;
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            }).then(resp => resp.text()).then(function(html){
                // 页面刷新
                document.open();
                document.write(html);
                document.close();
            }).catch(function(){
                alert('提交失败，请重试');
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        });
    }
}); 